package day_07;

import java.util.Arrays;

/**
 * @ClassName BinarySearch
 * @Description TODO
 * @Author hp
 * @Date 2021/6/10 11:36
 * @Version 1.0
 **/
public class BinarySearch {
    public static void main(String[] args) {
        int[] a = {1,11,3,12,5,13,8,10};
        System.out.println("binarySearch(a,4) = " + binarySearch(a, 11));
        System.out.println("Arrays.toString(a) = " + Arrays.toString(a));
    }
    public static int binarySearch(int[] x,int target){
        int[] arr = new int[x.length];
        System.arraycopy(x,0,arr,0,x.length);
        Arrays.sort(arr);
        int left = 0;
        int right = x.length;
        int mid ;
        int index = 0;
        while (left<=right){
            mid = (left+right)/2;
            if(target>arr[mid]){
                left = mid+1;

            }else if(target < arr[mid]){
                right = mid-1;

            }
            else {
                index = mid;
                break;
            }
        }
        return index;
    }
}
